from rest_framework import status
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from .serializers import WeChatLoginSerializer, TechnicianCertificationSerializer, UserSerializer
from .services import UserService


class AuthViewSet(GenericViewSet):
    """认证视图集"""
    permission_classes = [AllowAny]
    
    @action(detail=False, methods=['post'], permission_classes=[AllowAny])
    def wx_login(self, request):
        """微信登录"""
        serializer = WeChatLoginSerializer(data=request.data)
        if serializer.is_valid():
            try:
                code = serializer.validated_data['code']
                nickname = serializer.validated_data.get('nickname')
                avatar = serializer.validated_data.get('avatar')
                encrypted_data = serializer.validated_data.get('encrypted_data')
                iv = serializer.validated_data.get('iv')
                
                result = UserService.wechat_login(code, nickname, avatar, encrypted_data, iv)
                return Response(result)
            except ValueError as e:
                return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
    def userinfo(self, request):
        """获取当前用户信息"""
        serializer = UserSerializer(request.user)
        return Response(serializer.data)


class TechnicianViewSet(GenericViewSet):
    """技师视图集"""
    permission_classes = [IsAuthenticated]
    
    @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated])
    def certification(self, request):
        """技师认证申请"""
        serializer = TechnicianCertificationSerializer(data=request.data)
        if serializer.is_valid():
            try:
                result = UserService.technician_certification(request.user, serializer.validated_data)
                return Response(result, status=status.HTTP_201_CREATED)
            except ValueError as e:
                return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class UserViewSet(GenericViewSet):
    """用户视图集"""
    permission_classes = [IsAuthenticated]
    
    @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated])
    def switch_role(self, request):
        """角色切换"""
        new_role = request.data.get('role')
        try:
            result = UserService.switch_role(request.user, new_role)
            return Response(result)
        except ValueError as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        except PermissionError as e:
            return Response({'error': str(e)}, status=status.HTTP_403_FORBIDDEN)